<template>
  <div>
    <div class="card" style="margin-bottom:18px ">
      <el-input v-model="data.gameName" style="width: 280px;margin-right: 10px" placeholder="请输入赛事名称查询" :prefix-icon="Search"/>
<!--      <el-input v-model="data.gameType" style="width: 280px;margin-right: 10px" placeholder="请输入赛事类型查询" :prefix-icon="Search"/>-->
<!--&lt;!&ndash;      <el-input v-model="data.gymLocation" style="width: 280px;margin-right: 10px" placeholder="请输入票价类型查询" :prefix-icon="Search"/>&ndash;&gt;-->
      <!-- 修改为下拉选择框 -->
      <el-select v-model="data.gameType" style="width: 280px;margin-right: 10px" placeholder="请选择赛事类型">
        <el-option label="羽毛球" value="羽毛球" />
        <el-option label="足球" value="足球" />
        <el-option label="篮球" value="篮球" />
        <el-option label="排球" value="排球" />
        <el-option label="射击" value="射击" />
      </el-select>
      <el-button type="primary" plain style="margin-left: 10px"  @Click="load">查询</el-button>
      <el-button type="info" plain style="margin-left: 10px " @Click="reset">重置</el-button>
      <el-button type="success" plain @Click="handeladd" v-if="user.role === '管理员'">新增</el-button>
    </div>
  </div>
  <div class="card " style="margin-bottom:18px;">

    <div>
      <el-table :data="data.tableData" style="width: 100%">
        <el-table-column prop="id"  label="序号" width="60" />
        <el-table-column prop="gameId" label="赛事编号" width="80"/>
        <el-table-column prop="gameName" label="赛事名称" width="160"/>
        <el-table-column prop="ticketMoney1" label="贵宾票价" width="80" />
        <el-table-column prop="ticketQuantity1" label="贵宾票数量"  />
        <el-table-column prop="ticketMoney2" label="标准票价"  width="80"/>
        <el-table-column prop="ticketQuantity2" label="标准票数量"  />
        <el-table-column prop="ticketMoney3" label="低价票价"  width="80"/>
        <el-table-column prop="ticketQuantity3" label="低价票数量"  />
        <el-table-column prop="ticketCreateTime" label="售票开始时间"  />
        <el-table-column prop="ticketCloseTime" label="售票结束时间"  />
        <el-table-column label="操作" width="180" v-if="user.role === '管理员'">
          <template #default="scope">
            <el-button type="primary" plain  @Click="handeledit(scope.row)">编辑</el-button>
            <el-button type="danger" plain @Click="del(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" v-if="user.role === '普通用户'">
          <template #default="scope">
            <el-button type="primary" plain  @Click="handelebuy(scope.row)">购票</el-button>
<!--            <el-button type="danger" plain @Click="del(scope.row.id)">删除</el-button>-->
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
  <div class="card">
      <el-pagination v-model:page-size="data.pageSize" v-model:current-page="data.pageNum"
                     @current-change="handelCurrentChange"
                     background layout="prev, pager, next" :total="data.total" />
  </div>
  <el-dialog  width="35%" v-model="data.formVisible" title="票价信息" destroy-on-close>
    <el-form :model="data.form" :rules="rules" ref="formRef" label-width="100px" label-position="right" style="padding-right: 40px" >
      <el-form-item  prop="gameId" label="赛事编号" >
        <el-input v-model="data.form.gameId" autocomplete="off" placeholder="统一为1xx" />
      </el-form-item>
      <el-form-item prop="gameName" label="赛事名称" >
        <el-input  v-model="data.form.gameName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="贵宾票价" >
        <el-input v-model="data.form.ticketMoney1" autocomplete="off" />
      </el-form-item>
      <el-form-item label="贵宾票源数量" >
        <el-input v-model="data.form.ticketQuantity1" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="标准票价" >
        <el-input v-model="data.form.ticketMoney2" autocomplete="off" />
      </el-form-item>
      <el-form-item label="标准票源数量" >
        <el-input v-model="data.form.ticketQuantity2" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="低价票价" >
        <el-input v-model="data.form.ticketMoney3" autocomplete="off" />
      </el-form-item>
      <el-form-item label="低价票源数量" >
        <el-input v-model="data.form.ticketQuantity3" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="售票开始时间" >
        <el-input v-model="data.form.ticketCreateTime" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="售票结束时间" >
        <el-input v-model="data.form.ticketCloseTime" autocomplete="off"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="data.formVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">保 存</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog  width="55%" v-model="data.formVisiblebuy" title="购票信息" destroy-on-close>
    <el-form :model="data.form" :rules="rules1" ref="formRef1" label-width="100px" label-position="right" style="padding-right: 40px" >

      <el-form-item label="赛事编号：">
        <span>{{ data.form.gameId }}</span>
      </el-form-item>

      <el-form-item label="赛事名称：">
        <span>{{ data.form.gameName }}</span>
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="贵宾票价：">
            <span class="el-form-item__content">{{ data.form.ticketMoney1 }}元</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="票源数量：" >
            <span class="el-form-item__content">{{ data.form.ticketQuantity1 }}张</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="购买数量：" prop="tickets1">
            <el-input v-model="data.tickets1" autocomplete="off" placeholder="默认为0" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="标准票价：">
            <span class="el-form-item__content">{{ data.form.ticketMoney2 }}元</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="票源数量：">
            <span class="el-form-item__content">{{ data.form.ticketQuantity2 }}张</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="购买数量：" prop="tickets2">
            <el-input v-model="data.tickets2" autocomplete="off" placeholder="默认为0" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="低价票价：">
            <span class="el-form-item__content">{{ data.form.ticketMoney3 }}元</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="票源数量：">
            <span class="el-form-item__content">{{ data.form.ticketQuantity3 }}张</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="购买数量：" prop="tickets3" >
            <el-input v-model="data.tickets3" autocomplete="off" placeholder="默认为0" />
          </el-form-item>
        </el-col>

      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="售票开始：">
            <span class="el-form-item__content">{{ data.form.ticketCreateTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="售票结束：">
            <span class="el-form-item__content">{{ data.form.ticketCloseTime }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="总费用：">
        <span class="el-form-item__content">{{ calculateTotalCost() }}元</span>
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="温馨提示：">
            <span class="el-form-item__content">{{ data.buyticketsmessage }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="data.formVisiblebuy = false , resetnum()">取 消</el-button>
        <el-button type="primary" plain @click="buy(data.tickets1, data.tickets2, data.tickets3, data.form.gameId, user.id, calculateTotalCost())">购 买</el-button>
<!--        <el-button type="primary" @click="buy(tickets1,tickets2,tickets3,data.form.gameId,user.id)">购 买</el-button>-->
      </div>
    </template>
  </el-dialog>

</template>
<script setup>
import {reactive,ref} from "vue";
  import { Search } from '@element-plus/icons-vue'
  import request from "@/utils/request";
  import {ElMessage, ElMessageBox} from "element-plus";

  const baseurl='/ticket'
  const user = JSON.parse(localStorage.getItem('student-user')||'{}')

  const  data =reactive({
  gameName:"",
  gameType:"",
  total:0,
  tableData:[],
  pageNum: 1,//当前页数
  pageSize:10,//每一页的个数
  formVisible:false,
  formVisiblebuy:false,
  buyNum:0,
  tickets1:0,
  tickets2:0,
  tickets3:0,
  buyticketsmessage:"请勿重复购买，购买数量不能超过票源数量！谢谢配合",
  form:{},

})

  const load=() =>{
    request.get(baseurl +"/selectPage",{
      params:{
        pageNum: data.pageNum,
        pageSize: data.pageSize,
        gameName: data.gameName,
        gameType: data.gameType,
      }
    }).then(res=>{
    data.tableData = res.data?.list || []
      data.total = res.data.total || 0
    })
  }

  //调用方法获取数据
  load();

  const handelCurrentChange = () => {
  //翻页后重新加载数据页面
  load()
}

  const reset =()=>{
      data.gameName = ""
      data.gameType = ""
      load()
  }
  //取消
  // const cancel =()=>{
  //   data.formVisible = false
  //   data.formVisiblebuy = false
  // }


  const del =(id)=>{
    ElMessageBox.confirm('删除数据后无法回复，您确认删除吗？','删除确认',{type:'warning'}).then(res=> {
          request.delete(baseurl + '/delete/' + id).then(res => {
            if (res.code === '200') {
              load()
              ElMessage.success("删除成功")
            } else {
              ElMessage.error(res.msg)
            }
          })
        }) .catch(res => {})
  }

//表单校验
const rules = reactive({
  // username: [
  //   { required: true, message: '请输入账号', trigger: 'blur' },
  // ],
  // password: [
  //   { required: true, message: '请输入密码', trigger: 'blur' },
  // ],
})
//购票信息校验
const rules1 = reactive({
  tickets1: [
    {
      validator: (rule, value ,callback) => {

        const quantity = data.tickets1 || 0; // value 是从购票表单中获取的输入值，具体是 tickets1、tickets2 或 tickets3 的输入内容
        const remain = data.form.ticketQuantity1;

        if (quantity < 0) {
           callback(new Error('购买数量不能为负数'));

        } else if (quantity > remain) {
           callback(new Error(`购买数量最大为(${remain}张)`));

        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  tickets2: [
    {
      validator: (rule, value, callback) => {
        const quantity = data.tickets2 || 0;
        const remain = data.form.ticketQuantity2;

        if (quantity < 0) {
           callback(new Error('购买数量不能为负数'));

        } else if (quantity > remain) {
           callback(new Error(`购买数量最大为(${remain}张)`));

        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  tickets3: [
    {
      validator: (rule, value, callback) => {
        const quantity = data.tickets3 || 0;
        const remain = data.form.ticketQuantity3;

        if (quantity < 0) {
           callback(new Error('购买数量不能为负数'));

        } else if (quantity > remain) {
           callback(new Error(`购买数量最大为(${remain}张)`));

        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
} );
const calculateTotalCost = function () {
  const t1 = parseInt(data.tickets1) || 0;
  const t2 = parseInt(data.tickets2) || 0;
  const t3 = parseInt(data.tickets3) || 0;

  const price1 = parseFloat(data.form.ticketMoney1) || 0;
  const price2 = parseFloat(data.form.ticketMoney2) || 0;
  const price3 = parseFloat(data.form.ticketMoney3) || 0;

  return t1 * price1 + t2 * price2 + t3 * price3;
};


const formRef = ref()

const formRef1 = ref()
const handeladd =()=>{
  data.form= { }
  data.formVisible=true
}

const resetnum =()=>{
  data.tickets1  = 0
  data.tickets2  = 0
  data.tickets3  = 0
}

const handeledit =(row)=>{
  data.form=JSON.parse(JSON.stringify(row))
  data.formVisible=true;
}

const handelebuy =(row)=>{
  data.form=JSON.parse(JSON.stringify(row))
  data.formVisiblebuy=true;
}
  //保存数据到后台
const save =()=>{
    formRef.value.validate((valid) => {
      if(valid){
        request.request( {
          url:data.form.id ? baseurl + '/update': baseurl + '/add',
          method:data.form.id ? 'PUT' : 'POST',
          data:data.form
        }).then(res => {
          if (res.code ==='200'){
            load()
            data.formVisible = false //弹窗关闭
            ElMessage.success("操作成功")
          }else{
            ElMessage.error(res.msg)
          }
        })
      }
    })
  }


const buy = (tickets1, tickets2, tickets3, gameId, userId, totalCost) => {
  // 先校验表单
  formRef1.value.validate((valid) => {
    if (valid) {
      // 获取计算后的总费用
      //const totalCost = calculateTotalCost();

      // 调用后端接口（携带总费用）
      request.post(baseurl + '/addtickets', {
        tickets1,
        tickets2,
        tickets3,
        gameId,
        userId,
        totalCost
        //totalCost
      })
          .then(res => {
            if (res.code === '200') {
              load();
              data.formVisible = false;
              ElMessage.success("购票成功，总价：" + totalCost + "元");
              resetnum();
            } else {
              ElMessage.error(res.msg || "购票失败");
            }
          })
          .catch(error => {
            ElMessage.error("网络错误，请稍后重试");
          });
    } else {
      ElMessage.error('请检查购票数量');
      return false;
    }
  });
};


const handleImgUploadSuccess =(res=>{
  data.form.avatar=res.data

})

</script>